package com.example.rg1contactapp;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
//创建数据库
public class ContactDatabaseHelper extends SQLiteOpenHelper
{
    private Context context;
    //上下文？
    public ContactDatabaseHelper(Context context)
    {
        super(context,"mycontact.db",null,1);
        this.context=context;
    }
    //运行一次，创建数据表
    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {
        sqLiteDatabase.execSQL("CREATE TABLE information(_id INTEGER PRIMARY KEY AUTOINCREMENT," +
                "name VARCHAR(20),phone VARCHAR(20))");
    }
    //更新数据表
    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {

    }
    //插入
    public long insert(String name,String phone)
    {
        //获得对数据库操作的权限（读写）
        SQLiteDatabase sqLiteDatabase=this.getWritableDatabase();

        ContentValues values=new ContentValues();
        values.put("name",name);
        values.put("phone",phone);
        //获得插入数据的id
        long id=sqLiteDatabase.insert("information",null,values);
        if(id!=0)
        {
            Toast.makeText(context,"添加成功",Toast.LENGTH_SHORT).show();
        }
        //关闭数据库连接
        sqLiteDatabase.close();
        return id;
    }
    //查询
    public String queryByName(String name)
    {
        //获得对数据库操作的权限（可读）
        SQLiteDatabase sqLiteDatabase=this.getReadableDatabase();
        Cursor cursor= sqLiteDatabase.query("information",null,"name=?",
                new String[]{name},null,null,null);
        if(cursor.getCount()==0)
        {
            //关闭指针
            cursor.close();
            //关闭数据库连接
            sqLiteDatabase.close();
            return "NULL";
        }
        else
        {
            //指针  指到动到第一条数据那
            cursor.moveToFirst();
            //返回列的下标值
            String result=cursor.getString(2);
            cursor.close();
            sqLiteDatabase.close();
            return result;
        }
    }
    //查询所有
    public String queryAll()
    {
        SQLiteDatabase sqLiteDatabase=this.getReadableDatabase();
        Cursor cursor= sqLiteDatabase.query("information",null,null,
                null,null,null,null);
        if(cursor.getCount()==0)
        {
            cursor.close();
            sqLiteDatabase.close();
            return "NULL";
        }
        else
        {
            StringBuilder result=new StringBuilder();
            while(cursor.moveToNext())
            {
                result.append("Name:"+cursor.getString(1)+" ; "+"Phone:"+cursor.getString(2)+"\n");
            }
            cursor.close();
            sqLiteDatabase.close();
            return result.toString();
        }
    }


}
